<?php
// +----------------------------------------------------------------------
// | TwoThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.twothink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: 楹﹀綋鑻楀効 <zuojiazi@vip.qq.com> <http://www.zjzit.cn>
// +----------------------------------------------------------------------

namespace app\home\controller;
use app\home\model\Document;
use think\Cache;
class Index extends Home{
    public function __construct(){
        parent::__construct();
    }
    public function _initialize(){
        //parent::_initialize();
    }

    public static $orderIds = [
        
    ];
    public static $orders = [
        
    ];
    public static $allOrderIds = [];
    public static $noneedChangeOrderIds = [];
    public static $needChangeOrderIds = [];
    public static $goodsList = [];
    
    
    public function InitOrders(){
        $month = $this->month;
        //需要分配的订单
        $sql = "SELECT order_id from (
SELECT main.order_id,main.store_id,COUNT(DISTINCT main.store_id) as 'store_num' from 33hao_order_goods as main
LEFT JOIN 33hao_order as od on main.order_id = od.order_id
where od.add_time > UNIX_TIMESTAMP('{$month}') and od.add_time < UNIX_TIMESTAMP(DATE_ADD('{$month}',INTERVAL 1 month)) GROUP BY main.order_id
) as main where store_num > 1";
        $list = \think\Db::query($sql);
        echo \think\Db::name('33hao_order_goods')->getLastSql();
        if(!$list){
            return ;
        }
        foreach ($list as $row){
            self::$needChangeOrderIds[] = $row['order_id'];
        }
        $needchangeorderIds = implode(',', self::$needChangeOrderIds);
        //         var_dump(self::$needChangeOrderIds);die;
        $sql = "select * from 33hao_order_goods as main where order_id in ($needchangeorderIds)";
        $sql = "select main.*,og.goods_commonid,od.order_state from 33hao_order_goods  as main
LEFT JOIN 33hao_order as od on main.order_id = od.order_id
LEFT JOIN 33hao_goods as og  on main.goods_id = og.goods_id
where main.order_id in ($needchangeorderIds)";
        $list = \think\Db::query($sql);
        
        //初次分配
        foreach ($list as $index => $row){
            if(1){//一样的就不重新分配了
                if(!isset(self::$orders[$row['order_id']])){
                    $this->setOrderProduct($row['order_id'], $row,false);
                }elseif (self::$orders[$row['order_id']]['store_id'] == $row['store_id']){
                    $this->setOrderProduct($row['order_id'], $row,false);
                }else{
                    self::$goodsList[] = $row;
                }
            }
        }
//         var_dump(count(self::$needChangeOrderIds),count(self::$goodsList));die;
        
        //不需要分配的订单
        $sql = "SELECT order_id from (
SELECT main.order_id,main.store_id,COUNT(DISTINCT main.store_id) as 'store_num' from 33hao_order_goods as main
LEFT JOIN 33hao_order as od on main.order_id = od.order_id
where od.add_time > UNIX_TIMESTAMP('{$month}') and od.add_time < UNIX_TIMESTAMP(DATE_ADD('{$month}',INTERVAL 1 month)) GROUP BY main.order_id
) as main where store_num = 1";
        $list = \think\Db::query($sql);
        echo \think\Db::name('33hao_order_goods')->getLastSql();
        foreach ($list as $row){
            self::$noneedChangeOrderIds[] = $row['order_id'];
        }
        $noneedchangeorderIds = implode(',', self::$noneedChangeOrderIds);
        //         var_dump(self::$needChangeOrderIds);die;
        $sql = "select * from 33hao_order_goods as main where order_id in ($noneedchangeorderIds)";
        $sql = "select main.*,og.goods_commonid,od.order_state from 33hao_order_goods  as main
LEFT JOIN 33hao_order as od on main.order_id = od.order_id
LEFT JOIN 33hao_goods as og  on main.goods_id = og.goods_id
where main.order_id in ($noneedchangeorderIds)";
        $list = \think\Db::query($sql);
        //初次分配
        foreach ($list as $index => $row){
            if(1){//一样的就不重新分配了
                $this->setOrderProduct($row['order_id'], $row,false);
 /*                if(!isset(self::$orders[$row['order_id']])){
                    $this->setOrderProduct($row['order_id'], $row);
                }elseif (self::$orders[$row['order_id']]['store_id'] == $row['store_id']){
                    $this->setOrderProduct($row['order_id'], $row);
                }else{
                    //self::$goodsList[] = $row;
                } */
            }
            
        }
        
        self::$allOrderIds = array_merge(self::$needChangeOrderIds,self::$noneedChangeOrderIds);
        
        //剩余需要分配的产品
        foreach (self::$goodsList as $index => $row){
//             var_dump(self::$allOrderIds);
            shuffle(self::$allOrderIds);
//             var_dump(self::$orders);die;
            foreach (self::$allOrderIds as $order_id){
                $order = self::$orders[$order_id];
                if(empty($order)){
                    var_dump($order_id);die('empty order');
                }
                if(self::$orders[$order_id]['store_id'] != $row['store_id']){
                    continue;
                }
                if($order['order_state'] != $row['order_state']){//订单状态对应不上
                    echo 'order ' . $order_id .  '撞他对应不上 raw ' .$order['order_state'] . 'product ' . $row['order_state']. "\n";
                    continue;
                }
                if($order['amount'] > 2000 && $row['goods_price'] > 1000){//订单已2000 并下个产品金额大于 1000
                    continue;
                }
                if($order['amount'] > 4000){//订单总金额小于4000
                    continue;
                }
                $rand = rand(1,6);
                if($order['goods_num'] >= $rand){/* 产品个数 */
                    continue;
                }
                $rand2 = rand($order['goods_num'],10);
                if(($order['goods_num']=1 &&  $order['goods_count'] > 5) || ($order['goods_num'] >1 && $order['goods_count'] > $rand2) ){/* 产品总个数 */
                    //continue;
                }
                if(count($order['goods_commonid']) > 3){//平台货号不能超过3
                    continue;
                }
                $this->setOrderProduct($order_id, $row);
                unset(self::$goodsList[$index]);
                //消耗了 分配了就下一下产品
                break;
            }
        }
        //var_dump(self::$goodsList);
        return true;
    }

    public function setOrderProduct($order_id,$product,$update=true){
        if(!isset(self::$orders[$order_id])){
            self::$orders[$order_id] = [
                'store_id' => $product['store_id'],
                'order_state' => $product['order_state'],
                'amount'   => 0,
                'goods_ids' => [],
                'goods_num' => 0,//item数量
                'goods_count'=>0,//总数量
                'goods_commonid' => []
            ];
        }
        $order = self::$orders[$order_id];
        $order['amount'] += $product['goods_price'] * $product['goods_num'];
        !in_array($product['goods_id'], $order['goods_ids']) && $order['goods_num'] += 1;//产品个数
        $order['goods_count'] += $order['goods_num']; 
        !in_array($product['goods_commonid'], $order['goods_commonid']) && $order['goods_commonid'][] = $product['goods_commonid'];
        !in_array($product['goods_id'], $order['goods_ids']) && $order['goods_ids'][] = $product['goods_id'];
        
        $update && \think\Db::name('33hao_order_goods')->where(['rec_id'=>$product['rec_id']])->update(['order_id'=>$order_id]);
        
        self::$orders[$order_id] = $order;
        return true;
    }
    
    public $month ='2016-12-01';
	//每个月只一次
    public function index(){
        set_time_limit(0);
        $month = $this->month;
        $this->InitOrders();
        var_dump(count(self::$needChangeOrderIds),count(self::$goodsList));die;
        
        
        echo '1 step done'; die;
        //先保证每个订单有不少于30元的产品
        shuffle(self::$orderIds);
        foreach (self::$goodsList as $product){
            $order = self::$orders[$order_id];
            foreach ($products as $productIndex => $product){//分配产品
                if($product['goods_price'] < 30){
                    continue;
                }
                if($product['store_id'] != $order['store_id']){
                    continue;
                }
                $this->setOrderProduct($order_id, $order, $productIndex, $product);
                //消耗了 分配了就下一下产品
                unset($products[$productIndex]);
                break;
            }
        }
        echo '1 step done'; die;
        
        //然后继续
        foreach ($products as $productIndex => $product){//分配产品
            shuffle(self::$orderIds);
            foreach (self::$orderIds as $order_id){
                $order = self::$orders[$order_id];
                if($product['store_id'] != $order['store_id']){
                    continue;
                }
                if($order['amount'] == 0){//直接第一次分配
                    $this->setOrderProduct($order_id, $order, $productIndex, $product);
                    //消耗了 分配了就下一下产品
                    unset($products[$productIndex]);
                    break;
                }
                
                if($order['amount'] > 2000 && $product['goods_price'] > 1000){//订单已2000 并下个产品金额大于 1000
                    continue;
                }
                if($order['amount'] > 4000){//订单总金额小于4000
                    continue;
                }
                $rand = rand(1,6);
                if($order['goods_num'] >= $rand){/* 产品个数 */
                    continue;
                }
                $rand2 = rand($order['goods_num'],10);
                if(($order['goods_num']=1 &&  $order['goods_count'] > 5) || ($order['goods_num'] >1 && $order['goods_count'] > $rand2) ){/* 产品总个数 */
                    continue;
                }
                if(count($order['goods_commonid']) > 3){//平台货号不能超过3
                    continue;
                }
                $this->setOrderProduct($order_id, $order, $productIndex, $product);
                unset($products[$productIndex]);
                //消耗了 分配了就下一下产品
                break;
            }
        }
        echo '1 step done'; 
        //剩下的随机份了
        foreach ($products as $productIndex => $product){//分配产品
            shuffle(self::$orderIds);
            foreach (self::$orderIds as $order_id){
                $order = self::$orders[$order_id];
                if($product['store_id'] != $order['store_id']){
                    continue;
                }
                $rand = rand(3,6);
                if($order['goods_num'] >= $rand){/* 产品个数 */
                    continue;
                }
                $rand2 = rand($order['goods_num'],10);
                if(($order['goods_num']=1 &&  $order['goods_count'] > 5) || ($order['goods_num'] >1 && $order['goods_count'] > $rand2) ){/* 产品总个数 */
                    continue;
                }
                $this->setOrderProduct($order_id, $order, $productIndex, $product);
                unset($products[$productIndex]);
                //消耗了 分配了就下一下产品
                break;
            }
        }
        echo '1 step done'; 
    }
    
    
    public function check(){
        
        
        
        
        
        
        
        
        
        die('un use');
        
        
        set_time_limit(0);
        $month = $this->month;
        $data = [];
        $products = \think\Db::name('33hao_goods_tmp')->where(['month'=>$month,'leftt'=>['>',0]])->select();
        if(empty($products)){
            echo '2 step done ,not order_num leftt';die;
        }
//         var_dump($products);die;
        foreach ($products as $product){
            if(!$data[$product['store_id']]){
                $data[$product['store_id']] = [];
            }
            $data[$product['store_id']][$product['goods_id']] = $product;
        }
        unset($products);
        $ordersData = [];
        $orders = \think\Db::query("select * from 33hao_order_tmp where month='{$month}' order by rand();");
        $ordersGoods = \think\Db::query("select order_id,count(1) as 'count',sum(goods_num*goods_price) as 'total' from 33hao_order_goods_tmp where month='{$month}' group by order_id");
        $allTotoal = 0;
        foreach ($ordersGoods as $detail){
            if(!isset($ordersData[$detail['order_id']])){
                $ordersData[$detail['order_id']]['count'] = $detail['count'];
                $ordersData[$detail['order_id']]['total'] = $detail['total'];
                $ordersData[$detail['order_id']]['total_0'] = $detail['total'];
            }
            $allTotoal += $detail['total'];
        }
        unset($ordersGoods);
//         var_dump($ordersData);die;
        foreach ($data as $store_id => $list){
            if($allTotoal > 6700000){break;die('2 step done ,閿�鍞瓒冲浜�');}
            foreach ($list as $goods_id => $product){
                foreach ($orders as $order){
                    if(!isset($ordersData[$order['order_id']])){
                        $ordersData[$order['order_id']]['count'] = 1;//棣栨閮芥槸娣诲姞涓�涓殑
                        $ordersData[$order['order_id']]['total'] =50;//棣栨閮芥槸娣诲姞涓�涓殑
                        $ordersData[$order['order_id']]['total_0'] =50;//棣栨閮芥槸娣诲姞涓�涓殑
                    }
                    $count = $ordersData[$order['order_id']]['count'];
                    $total = $ordersData[$order['order_id']]['total'];
                    $total_0 = $ordersData[$order['order_id']]['total_0'];
                    $rand = rand(2,4);
                    $price = $product['goods_price'];
//                     var_dump($count,$rand,$price);die;
                    if(( $count > 6) || $count > 8 || $total_0 > 200 || $count > $rand || ($count > 1 && $price > 500) || $total > 5000){
                        continue;
                    }
                    //
                    if($data[$store_id][$goods_id]['leftt']  < 1){
                        unset($data[$store_id][$goods_id]);//鍒犻櫎浜у搧
                        break;
                    }
                    $num = $product['leftt'] > 10 ? rand(1,2) : 1;
                    \think\Db::query("insert into 33hao_order_goods_tmp (order_id,goods_id,goods_price,goods_num,gc_id,month) values ('" .$order['order_id']. "','{$goods_id}','{$price}','{$num}','". $product['gc_id'] ."','{$month}') ON DUPLICATE KEY UPDATE goods_num = goods_num + {$num}");
                    $data[$store_id][$goods_id]['leftt'] -= $num;
                    $ordersData[$order['order_id']]['count'] +=1;//娣诲姞涓�涓竴鏉¤褰�
                    $ordersData[$order['order_id']]['total'] +=$price * $num;//娣诲姞涓�涓竴鏉¤褰�
                    $allTotoal += $price * $num;//娣诲姞涓�涓竴鏉¤褰�
                    
                }
            }
        }
        //姣忔鍙墽琛屽畬閲嶆柊鏇存柊 浜у搧鍓╀綑鏁扮洰
        
        //鏇存柊鍓╀綑鏁伴噺
        \think\Db::query("update 33hao_goods_tmp set leftt=0 where month='{$month}'");//缃浂
        foreach ($data as $store_id => $list){
            foreach ($list as  $goods_id => $product){
                \think\Db::query("update 33hao_goods_tmp set leftt='".$data[$store_id][$goods_id]['leftt']."' where month='{$month}' and goods_id='$goods_id' and store_id='$store_id'");
            }
        }
        echo '2 step done';
    }

}
